<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="mode != 'folder'?4:24">
        <div class="head-container">
          <el-row style="display: flex;">
            <el-input
                v-model="folderName"
                placeholder="请输入文件夹名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
            />
            <el-button type="success" icon="el-icon-plus" size="mini" @click="addFolder" style="margin-left: 10px">新建</el-button>
          </el-row>
        </div>
        <div class="head-container" style="margin-top: 10px">
          <el-tree
              :data="folderList"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              class="fileList"
              @node-click="handleNodeClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
<!--                <el-button
                    type="text"
                    icon="el-icon-plus"
                    size="mini" @click.stop="addFolder(data)">新建</el-button>-->
                <el-dropdown size="mini" @command="(command) => handleCommand(command, data)">
                  <el-button
                      type="text"
                      icon="el-icon-more"
                      @click.stop
                      size="mini">更多</el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-plus" command="add">新建</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-edit" command="edit">重命名</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-folder-remove" command="move">移动</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-delete" command="delete">删除</el-dropdown-item>
<!--                    <el-dropdown-item icon="el-icon-circle-check" command="role" >分配</el-dropdown-item>-->
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" v-if="mode != 'folder'">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
          <el-form-item label="文件名称" prop="name">
            <el-input
                v-model="queryParams.name"
                placeholder="请输入文件名称"
                clearable
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['fileInfo:fileInfo:add']"
            >上传</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['fileInfo:fileInfo:add']"
            >批量导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['fileInfo:fileInfo:remove']"
            >删除</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="fileInfoList" @selection-change="handleSelectionChange" @row-click="selectRow">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="文件类型" align="center" prop="name" >
            <template slot-scope="scope">
              <svg-icon :icon-class="getIcon(scope.row.type)" style="font-size: 32px"/>
            </template>
          </el-table-column>
          <el-table-column label="文件名称" align="center" prop="name" />
          <el-table-column label="文件后缀" align="center" prop="type" />
          <el-table-column label="文件大小" align="center" prop="size" />
          <el-table-column label="创建人" align="center" prop="createBy" />
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click.stop="updateFolder(scope.row)"
                v-hasPermi="['fileInfo:fileInfo:edit']"
              >修改</el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click.stop="handleDelete(scope.row)"
                  v-hasPermi="['fileInfo:fileInfo:remove']"
              >删除</el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-download"
                  v-if="scope.row.type != 'folder'"
                  @click="handleDownload(scope.row)"
              >下载</el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-zoom-in"
                  v-if="scope.row.type != 'folder'"
                  @click="handlePreview(scope.row)"
              >预览</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-col>
    </el-row>

    <!-- 添加或修改文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择文件">
              <file-upload v-model="form.url" :fileType="false" :fileSize="600"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="seqNo">
              <el-input-number v-model="form.seqNo"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑文件夹" :visible.sync="openFolder" width="900px" append-to-body>
      <el-form ref="formFolder" :model="formFolder" :rules="rules" label-width="120px">
        <el-row>
            <el-col :span="24">
              <el-form-item label="父文件夹" v-if="formFolder.parentName">
                <el-input v-model="formFolder.parentName" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="文件夹名称" prop="name">
                <el-input v-model="formFolder.name" placeholder="请输入文件夹名称" maxlength="10"/>
              </el-form-item>
            </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="seqNo">
              <el-input-number v-model="formFolder.seqNo"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFolder">确 定</el-button>
        <el-button @click="openFolder = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="移动文件" :visible.sync="openMove" width="900px" append-to-body>
      <el-form ref="formFolder" :model="formFolder" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="父文件夹">
              <treeselect v-model="formFolder.parentId" :options="folderList" :show-count="true" placeholder="请选择归属文件夹" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFolder">确 定</el-button>
        <el-button @click="openMove = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="文件预览" :visible.sync="openPreview" v-if="openPreview" width="1300px" append-to-body>
      <file-preview :src="fileUrl"></file-preview>
    </el-dialog>
  </div>
</template>

<script>
import {queryFileInfo, getFileInfo, delFileInfo, addFileInfo, setFileInfoView} from "@/api/fileInfo/fileInfo";
import { addFolder, treeselectFileInfo, updateFolder } from '../../../api/fileInfo/fileInfo'
import FilePreview from "@/components/FilePreview/index"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "FileInfo",
  components:{Treeselect, FilePreview},
  data() {
    return {
      // 遮罩层
      loading: false,
      openPreview:false,
      fileUrl:"",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件表格数据
      fileInfoList: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      folderList:[],
      folderName:"",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openFolder:false,
      openMove:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: 0,
        ancestors: null,
        name: null,
        type: null,
        url: null,
        size: null
      },
      // 表单参数
      form: {},
      formFolder:{},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      },
      mode:"",
    };
  },
  created() {
    this.getFolderList();
    this.getList();
    this.mode = this.$route.query.mode
  },
  watch: {
    // 根据名称筛选部门树
    folderName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    selectRow(row){
      if (row.type == "folder"){
        this.queryParams.parentId = row.id;
        this.getList();
        this.$refs.tree.setCurrentKey(row.id);
      }
    },
    /** 删除按钮操作 */
    deleteFolder(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选择的数据项？').then(function() {
        return delFileInfo(ids);
      }).then(() => {
        this.getFolderList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleCommand(command,data){
      switch (command) {
        case "add":
          this.addFolder(data);
          break;
        case "edit":
          this.updateFolder(data);
          break;
        case "delete":
          this.deleteFolder(data);
          break;
        case "move":
          this.moveFolder(data);
          break;
        default:
          break;
      }
    },
    async getFolderList() {
      let res = await treeselectFileInfo({ type: "folder" })
      this.folderList = res.data;
    },
    moveFolder(data){
      this.reset();
      const id = data.id
      getFileInfo(id).then(response => {
        this.formFolder = response.data;
        this.openMove = true;
      });
    },
    /** 修改按钮操作 */
    updateFolder(data) {
      this.reset();
      const id = data.id
      getFileInfo(id).then(response => {
        this.formFolder = response.data;
        this.openFolder = true;
      });
    },
    addFolder(parentNode){
      if (parentNode){
        this.formFolder = {
          parentId:parentNode.id,
          parentName:parentNode.label,
          seqNo:1,
        }
      }else {
        this.formFolder= {
          parentId:0,
          seqNo:1,
        };
      }
      this.openFolder = true;
    },
    submitFolder(){
      this.$refs["formFolder"].validate(valid => {
        if (valid) {
          if (this.formFolder.id != null) {
            updateFolder(this.formFolder).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openFolder = false;
              this.openMove = false;
              this.getFolderList();
              this.getList();
            });
          } else {
            addFolder(this.formFolder).then(response => {
              this.$modal.msgSuccess("新建成功");
              this.openFolder = false;
              this.openMove = false;
              this.getFolderList();
              this.getList();
            });
          }
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.parentId = data.id;
      this.handleQuery();
    },
    /** 查询文件列表 */
    getList() {
      function sortItems(items) {
        return items.sort((a, b) => {
          if (a.type === 'folder' && b.type !== 'folder') {
            return -1;
          }
          if (a.type !== 'folder' && b.type === 'folder') {
            return 1;
          }
          return a.seqNo - b.seqNo;
        });
      }
      this.loading = true;
      queryFileInfo(this.queryParams).then(response => {
        let fileInfoList = response.data;
        this.fileInfoList = sortItems(fileInfoList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: this.queryParams.parentId,
        ancestors: null,
        name: null,
        type: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        url: null,
        seqNo:1,
        size: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新建按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addFileInfo(this.form).then(response => {
            this.$modal.msgSuccess("新建成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选择的数据项？').then(function() {
        return delFileInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fileInfo/fileInfo/export', {
        ...this.queryParams
      }, `fileInfo_${new Date().getTime()}.xlsx`)
    },
    handleDownload(row){
      window.open(process.env.VUE_APP_BASE_API+row.url)
    },
    handlePreview(row){
      let type = row.type;
      setFileInfoView({id:row.id})
      if (type == "pdf"){
        window.open(process.env.VUE_APP_BASE_API+row.url)
      }else {
        this.openPreview = true;
        this.fileUrl = process.env.VUE_APP_BASE_API+row.url;
      }
    },
  }
};
</script>
<style lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  .el-button [class*=el-icon-] + span{
    margin-left: 0px;
  }
}
</style>
